import React, { useState, useEffect, useCallback } from 'react';
import S from './index.m.less';

/**
 * @param {
 *   onChange,    // 默认value作为回调的参数
 *   maxLength,   // 最大数字
 *   placeholder  // 默认填充
 * } props
 */

export default function TextArea(props) {
    let timerOut; // 节流
    const clearT = useCallback(() => timerOut && clearTimeout(timerOut));
    const [Value, setValue] = useState('');
    useEffect(() => clearT, [clearT]);

    const { onChange, maxLength = 200, placeholder = '', style = {}, showLimit = true, value = "" } = props;
    const handleChange = e => {
        const { value } = e.target || {};
        clearT();
        timerOut = setTimeout(() => {
            const nValue = value.length > maxLength ? value.slice(0, maxLength) : value;
            setValue(nValue);
            onChange(nValue);
        }, 400);
    };

    return (
        <div className={S.tWrap}>
            <textarea className={S.content} style={style} maxLength={maxLength} placeholder={placeholder} onChange={handleChange}>
                {value}
            </textarea>

            {!!showLimit && (
                <div className={S.num}>
                    <span className={S.numleft}>{Value.length}</span>
                    <span className={S.numright}>{` / ${maxLength}`}</span>
                </div>)}
        </div>
    );
}
